<template>
  <view class="add-schedule-box">
    <HeaderNavTabarVue :title="'新建日程'" @leftIcon="leftIcon" />
    <input
      v-model="addScheduleBox.scheduleTitle"
      type="text"
      placeholder="日程、活动主题"
      class="header-input"
    />

    <view class="add-schedule-input-box">
      <view class="list-info">
        <view class="picker-content" @tap="participantsFn">
          <view class="measurement-info-list">
            <text class="info-list-left">添加参与人</text>
            <view class="info-list-right">
              <view v-if="addScheduleBox.participants.length > 0" class="uni-input">
                <text
                  v-for="(item, index) in addScheduleBox.participants"
                  :key="item.userId"
                  v-show="index < 3"
                  style="color: #165dff"
                  >{{ item.nickName }}{{ ' ' }}
                </text>
                <text v-show="addScheduleBox.participants.length > 3"> 等</text>
              </view>
              <view v-else class="uni-inputs">请选择</view>
              <i class="iconfont icon-youjiantou"></i>
            </view>
          </view>
        </view>
      </view>
      <view class="picker-content" @tap="toggle">
        <view class="measurement-info-list">
          <text class="info-list-left">开始时间</text>
          <view class="info-list-right">
            <view class="uni-input" v-if="addScheduleBox.datetimeValue">
              {{ dayjs(addScheduleBox.datetimeValue).format('MM月 DD日') }}
              周{{ weekDays[dayjs(addScheduleBox.datetimeValue).day()] }}
              {{ dayjs(addScheduleBox.datetimeValue).format('HH:mm') }}
            </view>
            <view class="uni-input" v-else>请选择</view>
            <i class="iconfont icon-youjiantou"></i>
          </view>
        </view>
      </view>

      <view class="picker-content" @tap="toggleHour">
        <view class="measurement-info-list" :class="{ bukabanci: !addScheduleBox.datetimeValue }">
          <text class="info-list-left">时长</text>
          <view class="info-list-right">
            <view class="info-content" style="display: flex; align-items: center">
              <view class="uni-input" v-if="addScheduleBox.hour">
                <p style="font-size: 28rpx; line-height: 1.4em">{{ addScheduleBox.hour }}</p>
              </view>
              <view class="uni-input" style="font-size: 28rpx; line-height: 1.4em" v-else
                >请选择会议时长
              </view>
            </view>
          </view>
        </view>
      </view>
      <view class="picker-content">
        <view class="measurement-info-list">
          <text class="info-list-left">全天</text>
          <view class="info-list-right">
            <view class="info-content" style="display: flex; align-items: center">
              <switch :checked="indicatorDots" @change="changeIndicatorDots" />
            </view>
          </view>
        </view>
      </view>
    </view>

    <uv-datetime-picker
      ref="datetimePicker"
      v-model="time"
      :formatter="formatter"
      mode="datetime"
      @confirm="confirm"
    />
    <uv-picker
      ref="toggleHourRef"
      :columns="pickerHourColumns"
      @confirm="pickerHourConfirm"
    ></uv-picker>
    <!--    说明附件-->
    <DescriptionAttachment @getDesignDrawingsEmit="getDesignDrawingsEmit" />
    <view class="textarea-box">
      <text class="info-list-left">描述</text>
      <textarea
        v-model="addScheduleBox.description"
        class="textinfo-list"
        placeholder="请输入"
      ></textarea>
    </view>

    <view class="picker-content" @tap="lableFn">
      <view class="measurement-info-list">
        <text class="info-list-left">标签</text>
        <view class="info-list-right">
          <view class="uni-input" v-if="addScheduleBox.lable">{{ addScheduleBox.lable }}</view>
          <view class="uni-inputs" v-else>请选择</view>
          <i class="iconfont icon-youjiantou"></i>
        </view>
      </view>
    </view>

    <uv-picker ref="lableRef" :columns="lableColumns" @confirm="lableConfirm"></uv-picker>
    <view class="button-container">
      <button class="button" @tap="handleSave">保存日程</button>
    </view>
  </view>
</template>

<script setup>
import HeaderNavTabarVue from '@/components/HeaderNavTabar/HeaderNavTabar.vue'
import MyPicker from '@/components/MyPicker/MyPicker.vue'
import { ref, watch } from 'vue'
import optionDeptPerson from '@/store/modules/optionDeptPerson'
import { onShow, onLoad } from '@dcloudio/uni-app'
import dayjs from 'dayjs'
import DescriptionAttachment from '@/components/audit/function/descriptionAttachment.vue'
import { getUserProfile } from '@/api/system/user'
import { addScheduleRecord } from '@/api/schedule'

let time = dayjs()
const indicatorDots = ref(false)
const weekDays = ['日', '一', '二', '三', '四', '五', '六']
const datetimePicker = ref(null)
const toggleHourRef = ref(null)

const addScheduleBox = ref({
  scheduleTitle: '',
  participants: [],
  datetimeValue: null,
  hour: 0,
  description: '',
  lable: '',
})
const lableRef = ref(null)
const lableColumns = [['工作事项', '会议', '外出']]
const pickerHourColumns = ref([[]])
const lableConfirm = (e) => {
  addScheduleBox.value.lable = e.value[0]
}
const pickerHourConfirm = (e) => {
  addScheduleBox.value.hour = e.value[0]
}
const lableFn = () => {
  lableRef.value.open()
}
const leftIcon = () => {
  console.log('leftIcon')
}
let attchment = ref([])
const userInfo = ref({
  userId: null,
  deptId: null,
  avatar: null,
  deptName: null,
  nickName: null,
})
const getDesignDrawingsEmit = (emit) => {
  attchment.value = emit
}
const participantsFn = () => {
  uni.navigateTo({
    url: '/components/OptionDeptPerson/index?type=person&noSelectSelf=1', // noSelectSelf 1 不能选择自身
  })
}
const confirm = (obj) => {
  addScheduleBox.value.datetimeValue = dayjs(obj.value).format('YYYY-MM-DD HH:mm')
}
const changeIndicatorDots = (v) => {
  indicatorDots.value = v.detail.value
}
const formatter = (type, value) => {
  if (type === 'year') {
    return `${value}年`
  }
  if (type === 'month') {
    return `${value}月`
  }
  if (type === 'day') {
    return `${value}日`
  }
  if (type === 'hour') {
    return `${value}时`
  }
  if (type === 'minute') {
    return `${value}分`
  }
  return value
}
// 打开选择器
const toggle = (type) => {
  datetimePicker.value.open()
}
const toggleHour = (type) => {
  if (addScheduleBox.value.datetimeValue) {
    toggleHourRef.value.open()
  }
}
onShow(() => {
  if (optionDeptPerson.state.optionPerson) {
    addScheduleBox.value.participants = optionDeptPerson.state.optionPerson.map((v) => {
      return {
        userId: v.userId,
        nickName: v.nickName,
        avatar: v.avatar,
        deptName: v.dept.deptName,
      }
    })
    addScheduleBox.value.participants.push({
      userId: userInfo.value.userId,
      nickName: userInfo.value.nickName,
      avatar: userInfo.value.avatar,
      deptName: userInfo.value.deptName,
    })
  }
})
const handleSave = async () => {
  let params = {
    attchment: JSON.stringify(attchment.value), // 附件
    reason: addScheduleBox.value.scheduleTitle,
    startTime: null, // 开始时间
    endTime: null, // 节结束间
    participants: JSON.stringify(addScheduleBox.value.participants), // 参会人
    describe: addScheduleBox.value.description, // 事由
    type: addScheduleBox.value.lable, // 类型
    userId: userInfo.value.userId, // 发起人
    deptId: userInfo.value.deptId, //
  }
  if (indicatorDots.value) {
    params.startTime = dayjs(addScheduleBox.value.datetimeValue).format('YYYY-MM-DD 00:00:00') // 开始时间
    params.endTime = dayjs(addScheduleBox.value.datetimeValue).format('YYYY-MM-DD 23:59:00') // 节结束间
  } else {
    params.startTime = dayjs(addScheduleBox.value.datetimeValue).format('YYYY-MM-DD HH:mm:ss')
      ? dayjs(addScheduleBox.value.datetimeValue).format('YYYY-MM-DD HH:mm:ss')
      : null // 开始时间
    params.endTime = addScheduleBox.value.datetimeValue
      ? dayjs(
          dayjs(addScheduleBox.value.datetimeValue).add(
            Number(addScheduleBox.value.hour.replace('小时', '')),
            'hour',
          ),
        ).format('YYYY-MM-DD HH:mm:00')
      : null //
  }
  let { code } = await addScheduleRecord(params)
  if (code === 200) {
    uni.showToast({
      icon: 'success',
      title: '添加成功',
    })
    setTimeout(() => {
      uni.navigateBack()
    }, 500)
  }
}
watch(
  () => addScheduleBox.value.datetimeValue,
  (val) => {
    const midnight = dayjs(val).endOf('day') // '2025-01-18 23:59:59'，即当天晚上零点前的一刻
    const hoursUntilMidnight = midnight.diff(val, 'hour')
    pickerHourColumns.value[0] = Array.from(
      { length: hoursUntilMidnight + 1 },
      (_, index) => (index + 1).toString() + '小时',
    )
  },
)

onLoad(() => {
  if(optionDeptPerson.state.optionPerson){
    optionDeptPerson.mutations.clearOptionPerson(optionDeptPerson.state)
  }
  getUserProfile().then((res) => {
    userInfo.value.userId = res.data.userId
    userInfo.value.deptId = res.data.deptId
    userInfo.value.nickName = res.data.nickName
    userInfo.value.avatar = res.data.avatar
    userInfo.value.deptName = res.data.dept.deptName

  })
})
</script>

<style scoped lang="scss">
@import '/static/style/index.scss';

.button-container {
  display: flex;
  width: 100%;
  height: 120rpx;
  align-items: center;
  background: #fff;

  .button {
    width: 100%;
    margin: 0 24rpx 0 24rpx;
    height: 72rpx;
    background: #165dff;
    color: #fff;
    font-size: 32rpx;
    font-weight: 500;
    line-height: 44.8rpx;
    display: flex;
    justify-content: center;
    align-items: center;
    border: none;
    border-radius: 8rpx;
  }
}

.add-schedule-box {
  .bukabanci {
    .info-content {
      color: #86909c !important;
    }

    .info-list-left {
      // @include font-color-auxiliary;
      color: #86909c !important;
    }
  }

  .header-input {
    height: 104rpx;
    padding: 22rpx 32rpx;
    background: #fff;

    &::placeholder {
      color: #c9cdd4;
      font-size: 34rpx;
      font-style: normal;
      font-weight: 500;
    }
  }

  .textarea-box {
    background: #fff;
    padding: 32rpx;
  }

  .add-schedule-input-box {
    background: #fff;
  }

  .measurement-info-list {
    @include flex($align: center, $justify: space-between);
    padding: $spacing-row-base;
    background: #fff;
    margin-top: 16rpx;

    .info-list-left {
      // @include font-color-auxiliary;
      color: #1d2129;
      font-size: $font-size-base;
    }

    .info-list-right {
      @include flex($align: center);

      .info-content {
        @include textStyleBase;
        font-size: 34rpx;
      }

      .iconfont {
        margin-left: 16rpx;
        // @include font-color-auxiliary;
        color: $uni-fc-fu-lin;
      }
    }

    .unit {
      // @include font-color-auxiliary;
      color: $uni-fc-fu-lin;
    }
  }
}
</style>
